<template>
  <div class="ticket-management">
    <!-- 统计卡片区域 -->
    <el-card class="stats-card" :body-style="{ padding: '15px' }">
      <h2 class="section-title">📊 工单统计</h2>
      <div class="stats-container">
        <StatisticCard
          label="待审核"
          :value="statistics.pendingReview.toString()"
          icon="el-icon-time"
          type="warning"
        />
        <StatisticCard
          label="已通过"
          :value="statistics.approved.toString()"
          icon="el-icon-check-circle"
          type="success"
        />
        <StatisticCard
          label="已拒绝"
          :value="statistics.rejected.toString()"
          icon="el-icon-circle-close"
          type="danger"
        />
        <StatisticCard
          label="处理中"
          :value="statistics.processing.toString()"
          icon="el-icon-loading"
          type="primary"
        />
        <StatisticCard
          label="已完成"
          :value="statistics.completed.toString()"
          icon="el-icon-check"
          type="success"
        />
        <StatisticCard
          label="总工单"
          :value="statistics.total.toString()"
          icon="el-icon-files"
          type="info"
        />
      </div>
    </el-card>

    <!-- 筛选区域 -->
    <el-card class="filter-card" :body-style="{ padding: '15px' }">
      <div v-if="isFilterExpanded" class="filter-content">
        <DynamicForm
          ref="searchFormRef"
          v-model="filterForm"
          :form-config="filterFormConfig"
          :gutter="16"
          label-width="100px"
          type="search"
          @search="handleSearch"
          @reset="handleReset"
        >
        </DynamicForm>
      </div>
    </el-card>

    <!-- 工单列表 -->
    <el-card class="table-card" :body-style="{ padding: '15px' }">
      <DynamicTable
        ref="tableRef"
        :data="list"
        :columns="tableColumns"
        :loading="loading"
        :pagination="pagination"
        selection-type="multiple"
        row-key="id"
        border
        @selection-change="handleSelectionChange"
        @size-change="handleSizeChange"
        @current-page-change="handlePageChange"
      >
        <template #toolbar-left>
          <div class="action-bar">
            <el-button
              type="primary"
              @click="openBatchReview"
              :disabled="selectedRows.length === 0"
            >
              批量审核
            </el-button>
            <el-button
              type="primary"
              @click="handleBatchPush"
              :disabled="selectedRows.length === 0"
            >
              批量推送
            </el-button>
            <el-button
              type="warning"
              @click="openBatchClose"
              :disabled="selectedRows.length === 0"
            >
              批量关闭
            </el-button>
            <el-button type="primary" @click="handleExport" class="export-btn">
              导出Excel
            </el-button>
            <span class="selected-count" v-if="selectedRows.length > 0">
              已选: {{ selectedRows.length }} 项
            </span>
            <div class="sort-container">
              <span>排序: </span>
              <el-select
                v-model="sortConfig.sortBy"
                @change="handleSortChange"
                size="small"
              >
                <el-option label="创建时间" value="created_time" />
                <el-option label="工单ID" value="ticket_id" />
                <el-option label="优先级" value="priority" />
              </el-select>
              <el-button
                type="text"
                icon="el-icon-arrow-up"
                @click="toggleSortOrder"
                :disabled="sortConfig.sortBy === ''"
                :class="{ 'active-sort': sortConfig.sortOrder === 'asc' }"
              />
              <el-button
                type="text"
                icon="el-icon-arrow-down"
                @click="toggleSortOrder"
                :disabled="sortConfig.sortBy === ''"
                :class="{ 'active-sort': sortConfig.sortOrder === 'desc' }"
              />
            </div>
          </div>
        </template>
        <template #priority="{ row }">
          <el-tag
            :type="
              row.priority === 'critical'
                ? 'danger'
                : row.priority === 'high'
                ? 'warning'
                : row.priority === 'medium'
                ? 'info'
                : 'success'
            "
          >
            {{ row.priority_name || row.priority }}
          </el-tag>
        </template>
        <template #status="{ row }">
          <el-tag
            :type="
              row.ticket_status === 'pending_review'
                ? 'warning'
                : row.ticket_status === 'approved'
                ? 'success'
                : row.ticket_status === 'rejected'
                ? 'danger'
                : row.ticket_status === 'processing'
                ? 'info'
                : row.ticket_status === 'completed'
                ? 'success'
                : row.ticket_status === 'pushed'
                ? 'info'
                : 'info'
            "
          >
            {{
              statusMap[row.ticket_status] ||
              row.ticket_status_name ||
              row.ticket_status
            }}
          </el-tag>
        </template>
        <template #action="{ row }">
          <el-button size="small" @click="openDetailModal(row)" type="info">
            详情
          </el-button>
          <el-button
            v-if="row.ticket_status === 'pending_review'"
            size="small"
            @click="handleOpenReview(row)"
            type="primary"
          >
            审核
          </el-button>
          <el-button
            v-if="row.ticket_status === 'approved'"
            size="small"
            @click="handleSinglePush(row)"
            type="success"
          >
            推送OA
          </el-button>
          <el-button
            v-if="
              row.ticket_status === 'resolved' ||
              row.ticket_status === 'completed'
            "
            size="small"
            @click="handleOpenClose(row)"
            type="warning"
          >
            关闭
          </el-button>
        </template>
      </DynamicTable>
    </el-card>

    <!-- 工单详情弹窗 -->
    <DetailModal v-model="detailVisible" :ticket="currentTicket" />

    <!-- 工单审核弹窗 -->
    <ReviewModal
      v-model="reviewVisible"
      :ticket="currentReviewTicket"
      @reviewed="handleTicketReviewed"
    />

    <!-- 批量审核弹窗 -->
    <el-dialog
      v-model="batchReviewVisible"
      title="批量审核"
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="batch-review-dialog">
        <el-alert
          title="批量审核提示"
          type="warning"
          :closable="false"
          style="margin-bottom: 20px"
        >
          已选择 {{ selectedRows.length }} 个工单，请选择审核决策并填写意见
        </el-alert>

        <div
          class="selected-tickets"
          style="max-height: 200px; overflow-y: auto; margin-bottom: 20px"
        >
          <el-tag
            v-for="ticket in selectedRows"
            :key="ticket.ticket_id"
            style="margin: 5px"
          >
            {{ ticket.ticket_id }} - {{ ticket.responsible_person }} -
            {{ ticket.ticket_type_name }}
          </el-tag>
        </div>

        <el-form :model="batchReviewForm" label-width="80px">
          <el-form-item label="审核决策">
            <el-radio-group v-model="batchReviewForm.decision">
              <el-radio value="approved">通过</el-radio>
              <el-radio value="rejected">拒绝</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="审核意见">
            <el-input
              v-model="batchReviewForm.comment"
              type="textarea"
              :rows="4"
              placeholder="请输入审核意见（必填）"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <el-button @click="batchReviewVisible = false">取消</el-button>
        <el-button type="primary" @click="submitBatchReview">
          批量提交
        </el-button>
      </template>
    </el-dialog>

    <!-- 单个关闭工单弹窗 -->
    <el-dialog
      v-model="closeVisible"
      title="关闭工单"
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="close-ticket-dialog">
        <el-alert
          title="关闭工单提示"
          type="warning"
          :closable="false"
          style="margin-bottom: 20px"
        >
          确定要关闭工单
          {{ currentCloseTicket.ticket_id }} 吗？关闭后不可再修改。
        </el-alert>

        <el-form
          :model="closeForm"
          :rules="closeRules"
          ref="closeFormRef"
          label-width="100px"
        >
          <el-form-item label="关闭原因" prop="close_reason">
            <el-input
              v-model="closeForm.close_reason"
              type="textarea"
              :rows="4"
              placeholder="请输入关闭原因（必填）"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="关闭备注" prop="close_note">
            <el-input
              v-model="closeForm.close_note"
              type="textarea"
              :rows="3"
              placeholder="请输入关闭备注（可选）"
              maxlength="1000"
              show-word-limit
            />
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <el-button @click="closeVisible = false">取消</el-button>
        <el-button type="warning" @click="submitClose"> 确认关闭 </el-button>
      </template>
    </el-dialog>

    <!-- 批量关闭工单弹窗 -->
    <el-dialog
      v-model="batchCloseVisible"
      title="批量关闭工单"
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="batch-close-dialog">
        <el-alert
          title="批量关闭提示"
          type="warning"
          :closable="false"
          style="margin-bottom: 20px"
        >
          已选择 {{ selectedRows.length }} 个工单，请填写关闭原因和备注
        </el-alert>

        <div
          class="selected-tickets"
          style="max-height: 200px; overflow-y: auto; margin-bottom: 20px"
        >
          <el-tag
            v-for="ticket in selectedRows"
            :key="ticket.ticket_id"
            style="margin: 5px"
          >
            {{ ticket.ticket_id }} -
            {{ ticket.assignee_name || ticket.responsible_person || "-" }} -
            {{ ticket.ticket_type_name || ticket.ticket_type || "-" }}
          </el-tag>
        </div>

        <el-form
          :model="batchCloseForm"
          :rules="batchCloseRules"
          ref="batchCloseFormRef"
          label-width="100px"
        >
          <el-form-item label="关闭原因" prop="close_reason">
            <el-input
              v-model="batchCloseForm.close_reason"
              type="textarea"
              :rows="4"
              placeholder="请输入关闭原因（必填）"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="关闭备注" prop="close_note">
            <el-input
              v-model="batchCloseForm.close_note"
              type="textarea"
              :rows="3"
              placeholder="请输入关闭备注（可选）"
              maxlength="1000"
              show-word-limit
            />
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <el-button @click="batchCloseVisible = false">取消</el-button>
        <el-button type="warning" @click="submitBatchClose">
          批量关闭
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import DynamicForm from "@/components/DynamicForm/index.vue";
import DynamicTable from "@/components/DynamicTable/index.vue";
import type { DynamicFormInstance } from "@/components/DynamicForm/types";
import type { DynamicTableInstance } from "@/components/DynamicTable/types";
import type { FormItemConfig } from "@/components/DynamicForm/types";
import type {
  TableColumn,
  PaginationConfig,
} from "@/components/DynamicTable/types";
import StatisticCard from "./components/StatisticCard.vue";
import DetailModal from "./components/DetailModal.vue";
import ReviewModal from "./components/ReviewModal.vue";
import {
  getTicketList,
  getTicketStatistics,
  getTicketFilterOptions,
  getTicketDetail,
  reviewTicket,
  batchReviewTickets,
  pushTickets,
  exportTicketExcel,
  closeTicket,
  batchCloseTickets,
} from "../../servers";

// 页面状态
const username = ref("张三");
const isFilterExpanded = ref(true);
const loading = ref(false);
const selectedRows = ref<any[]>([]);
const detailVisible = ref(false);
const currentTicket = ref<any>({});
const reviewVisible = ref(false);
const currentReviewTicket = ref<any>({});
const batchReviewVisible = ref(false);
const batchReviewForm = reactive({
  decision: "approved" as "approved" | "rejected",
  comment: "",
});
const closeVisible = ref(false);
const currentCloseTicket = ref<any>({});
const closeFormRef = ref<any>(null);
const closeForm = reactive({
  close_reason: "",
  close_note: "",
});
const closeRules = {
  close_reason: [
    { required: true, message: "请输入关闭原因", trigger: "blur" },
    { max: 500, message: "关闭原因不能超过500字", trigger: "blur" },
  ],
};
const batchCloseVisible = ref(false);
const batchCloseFormRef = ref<any>(null);
const batchCloseForm = reactive({
  close_reason: "",
  close_note: "",
});
const batchCloseRules = {
  close_reason: [
    { required: true, message: "请输入关闭原因", trigger: "blur" },
    { max: 500, message: "关闭原因不能超过500字", trigger: "blur" },
  ],
};

// 统计信息
const statistics = reactive({
  pendingReview: 0,
  approved: 0,
  rejected: 0,
  processing: 0,
  completed: 0,
  total: 0,
});

// 筛选表单
const searchFormRef = ref<DynamicFormInstance>();
const filterForm = reactive({
  ticket_status: "",
  ticket_type: "",
  priority: "",
  responsible_person: "",
  department: "",
  reviewer_name: "",
  start_time: "",
  end_time: "",
  keyword: "",
});

// 排序配置
const sortConfig = reactive({
  sortBy: "created_time",
  sortOrder: "desc" as "asc" | "desc",
});

// 筛选选项（从接口获取）
const filterOptions = reactive({
  departments: [] as string[],
  responsible_persons: [] as string[],
  ticket_types: [] as Array<{ value: string; label: string }>,
  ticket_statuses: [] as Array<{ value: string; label: string }>,
  priorities: [] as Array<{ value: string; label: string }>,
  reviewers: [] as string[],
});

// 筛选表单配置（动态从接口获取选项）
const filterFormConfig = computed<FormItemConfig[]>(() => [
  {
    key: "ticket_status",
    name: "工单状态",
    type: "select",
    placeholder: "请选择工单状态",
    params: { clearable: true },
    options: filterOptions.ticket_statuses.map((item) => ({
      label: item.label,
      value: item.value,
    })),
  },
  // {
  //   key: "ticket_type",
  //   name: "工单类型",
  //   type: "select",
  //   placeholder: "请选择工单类型",
  //   params: { clearable: true },
  //   options: filterOptions.ticket_types.map((item) => ({
  //     label: item.label,
  //     value: item.value,
  //   })),
  //   col: { span: 6 },
  // },
  {
    key: "priority",
    name: "优先级",
    type: "select",
    placeholder: "请选择优先级",
    params: { clearable: true },
    options: filterOptions.priorities.map((item) => ({
      label: item.label,
      value: item.value,
    })),
  },
  // {
  //   key: "reviewer_name",
  //   name: "审核人",
  //   type: "select",
  //   placeholder: "请选择审核人",
  //   params: { clearable: true },
  //   options: filterOptions.reviewers.map((reviewer) => ({
  //     label: reviewer,
  //     value: reviewer,
  //   })),
  //   col: { span: 6 },
  // },
  {
    key: "department",
    name: "部  门",
    type: "select",
    placeholder: "请选择部门",
    params: { clearable: true },
    options: filterOptions.departments.map((dept) => ({
      label: dept,
      value: dept,
    })),
  },
  {
    key: "time",
    name: "时间范围",
    type: "date",
    placeholder: "请选择时间范围",
    params: {
      type: "daterange", // 设置为日期范围选择器
      format: "YYYY-MM-DD",
      valueFormat: "YYYY-MM-DD",
      clearable: true,
      rangeSeparator: "至",
      startPlaceholder: "开始日期",
      endPlaceholder: "结束日期",
    },
    col: { span: 6 },
  },
  // {
  //   key: "start_time",
  //   name: "开始时间",
  //   type: "date",
  //   placeholder: "请选择开始时间",
  //   params: {
  //     format: "YYYY-MM-DD",
  //     valueFormat: "YYYY-MM-DD HH:mm:ss",
  //     clearable: true,
  //   },
  //   col: { span: 6 },
  // },
  // {
  //   key: "end_time",
  //   name: "结束时间",
  //   type: "date",
  //   placeholder: "请选择结束时间",
  //   params: {
  //     format: "YYYY-MM-DD",
  //     valueFormat: "YYYY-MM-DD HH:mm:ss",
  //     clearable: true,
  //   },
  //   col: { span: 6 },
  // },
  {
    key: "keyword",
    name: "IP/关键词",
    type: "input",
    placeholder: "请输入IP或关键词",
    col: { span: 6 },
  },
]);

// 状态映射
const statusMap: Record<string, string> = {
  pending_review: "待审核",
  approved: "已通过",
  rejected: "已拒绝",
  pushed: "已推送",
  processing: "处理中",
  completed: "已完成",
  closed: "已关闭",
};

// 表格列配置
const tableColumns: TableColumn[] = [
  { label: "工单ID", prop: "ticket_id", minWidth: 120 },
  {
    label: "工单类型",
    prop: "ticket_type",
    formatter: (row) => {
      // 从 ticket_description 中提取场景类型，或使用默认值
      if (row.ticket_description) {
        const match = row.ticket_description.match(/场景类型:\s*([^\n]+)/);
        if (match) {
          return match[1].trim();
        }
      }
      return row.ticket_type_name || row.ticket_type || "-";
    },
  },
  {
    label: "责任人",
    prop: "assignee_name",
    formatter: (row) => {
      return row.assignee_name || row.responsible_person || "-";
    },
    minWidth: 100,
  },
  {
    label: "部门",
    prop: "assignee_department",
    formatter: (row) => {
      return row.assignee_department || row.responsible_department || "-";
    },
    minWidth: 100,
  },
  {
    label: "状态",
    prop: "ticket_status",
    slot: "status",
    minWidth: 100,
  },
  {
    label: "优先",
    prop: "priority",
    slot: "priority",
    minWidth: 80,
  },
  { label: "告警数", prop: "alert_count", minWidth: 80, align: "center" },
  {
    label: "操作",
    width: 180,
    fixed: "right",
    slot: "action",
  },
];

// 表格数据
const list = ref<any[]>([]);

// 分页配置
const pagination = reactive<PaginationConfig>({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pageSizes: [10, 20, 50, 100],
  layout: "total, sizes, prev, pager, next, jumper",
  background: true,
});

// 表格引用
const tableRef = ref<DynamicTableInstance>();

// 获取筛选选项
const fetchFilterOptions = async () => {
  try {
    const { data } = await getTicketFilterOptions();
    if (data) {
      filterOptions.departments = data.departments || [];
      filterOptions.responsible_persons = data.responsible_persons || [];
      filterOptions.ticket_types = data.ticket_types || [];
      filterOptions.ticket_statuses = data.ticket_statuses || [];
      filterOptions.priorities = data.priorities || [];
      filterOptions.reviewers = data.reviewers || [];
    }
  } catch (error: any) {
    console.error("获取筛选选项失败:", error);
  }
};

// 获取统计数据
const fetchStatistics = async () => {
  try {
    const params: any = {};
    if (filterForm.start_time) {
      params.start_time = filterForm.start_time;
    }
    if (filterForm.end_time) {
      params.end_time = filterForm.end_time;
    }

    const { data } = await getTicketStatistics(params);
    if (data) {
      // 根据API返回的数据结构映射字段
      // by_status 中的每个状态都有 count 和 name 字段
      statistics.pendingReview = data.by_status?.pending_review?.count || 0;
      statistics.approved = data.by_status?.approved?.count || 0;
      statistics.rejected = data.by_status?.rejected?.count || 0;
      statistics.processing =
        data.by_status?.processing?.count || data.processing_count || 0;
      statistics.completed =
        data.by_status?.resolved?.count || data.resolved_count || 0;
      statistics.total = data.total_count || 0;
    }
  } catch (error: any) {
    console.error("获取统计数据失败:", error);
  }
};

// 获取工单列表
const fetchList = async (values: any = {}) => {
  console.log(123, "2222222");
  loading.value = true;
  try {
    const params: any = {
      page: pagination.currentPage,
      per_page: pagination.pageSize,
      sort_by: sortConfig.sortBy,
      sort_order: sortConfig.sortOrder,
      ...values,
    };

    // 添加筛选条件
    // if (filterForm.ticket_status) {
    //   params.ticket_status = filterForm.ticket_status;
    // }
    // if (filterForm.ticket_type) {
    //   params.ticket_type = filterForm.ticket_type;
    // }
    // if (filterForm.priority) {
    //   params.priority = filterForm.priority;
    // }
    // if (filterForm.responsible_person) {
    //   params.responsible_person = filterForm.responsible_person;
    // }
    // if (filterForm.department) {
    //   params.department = filterForm.department;
    // }
    // if (filterForm.reviewer_name) {
    //   params.reviewer_name = filterForm.reviewer_name;
    // }
    // if (filterForm.start_time) {
    //   params.start_time = filterForm.start_time;
    // }
    // if (filterForm.end_time) {
    //   params.end_time = filterForm.end_time;
    // }
    // if (filterForm.keyword) {
    //   params.keyword = filterForm.keyword;
    // }

    const { data } = await getTicketList(params);
    if (data) {
      list.value = data.items || [];
      pagination.total = data.pagination?.total || 0;
    }
  } catch (error: any) {
    ElMessage.error(error?.message || "获取工单列表失败");
  } finally {
    loading.value = false;
    fetchStatistics();
  }
};

// 筛选操作
const handleReset = () => {
  searchFormRef.value?.resetFields();
  pagination.currentPage = 1;
  fetchList();
};

const handleSearch = (values: any) => {
  pagination.currentPage = 1;
  fetchList(values);
};

// 导出Excel
const handleExport = async () => {
  try {
    loading.value = true;
    // 构建导出参数（与列表筛选参数一致）
    const params: any = {
      ...filterForm,
      sort_by: sortConfig.sortBy,
      sort_order: sortConfig.sortOrder,
    };

    const result = await exportTicketExcel(params);
    // 处理文件下载
    const blob = new Blob([result.data], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `工单列表_${new Date().toLocaleDateString()}.xlsx`;
    document.body.appendChild(a);
    a.click();
    window.URL.revokeObjectURL(url);
    document.body.removeChild(a);

    ElMessage.success("Excel导出成功");
  } catch (error: any) {
    ElMessage.error(error?.message || "导出失败");
  } finally {
    loading.value = false;
  }
};

// 表格选择
const handleSelectionChange = (rows: any[]) => {
  selectedRows.value = rows;
};

// 分页操作
const handlePageChange = (page: number) => {
  pagination.currentPage = page;
  fetchList();
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  fetchList();
};

// 排序操作
const handleSortChange = () => {
  fetchList();
};

const toggleSortOrder = () => {
  sortConfig.sortOrder = sortConfig.sortOrder === "asc" ? "desc" : "asc";
  fetchList();
};

// 弹窗控制
const openDetailModal = async (row: any) => {
  try {
    loading.value = true;
    const { data } = await getTicketDetail({ ticket_id: row.ticket_id });
    if (data) {
      currentTicket.value = data;
      detailVisible.value = true;
    }
  } catch (error: any) {
    ElMessage.error(error?.message || "获取工单详情失败");
  } finally {
    loading.value = false;
  }
};

// 打开审核弹窗
const handleOpenReview = (ticket: any) => {
  currentReviewTicket.value = ticket;
  reviewVisible.value = true;
  detailVisible.value = false;
};

// 工单审核后的回调
const handleTicketReviewed = () => {
  fetchList();
};

// 打开批量审核弹窗
const openBatchReview = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请先选择要审核的工单");
    return;
  }

  // 检查是否都是待审核状态
  const hasPending = selectedRows.value.every(
    (ticket) => ticket.ticket_status === "pending_review"
  );

  if (!hasPending) {
    ElMessage.warning("只能审核待审核状态的工单");
    return;
  }

  batchReviewForm.decision = "approved";
  batchReviewForm.comment = "";
  batchReviewVisible.value = true;
};

// 提交批量审核
const submitBatchReview = async () => {
  if (!batchReviewForm.comment.trim()) {
    ElMessage.warning("请填写审核意见");
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要批量${getDecisionText(batchReviewForm.decision)} ${
        selectedRows.value.length
      } 个工单吗？`,
      "确认批量审核",
      {
        type: "warning",
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      }
    );

    loading.value = true;
    const ticketIds = selectedRows.value.map((ticket) => ticket.ticket_id);

    const result = await batchReviewTickets({
      ticket_ids: ticketIds,
      review_decision: batchReviewForm.decision,
      review_comment: batchReviewForm.comment,
    });

    if (result?.data) {
      const { success_count, failed_count, total_count } = result.data;

      if (failed_count === 0) {
        ElMessage.success(`批量审核成功！共处理 ${total_count} 个工单`);
      } else {
        ElMessage.warning(
          `批量审核完成！成功 ${success_count} 个，失败 ${failed_count} 个`
        );
      }
    } else {
      ElMessage.success(result?.message || "批量审核成功");
    }

    selectedRows.value = [];
    batchReviewVisible.value = false;
    fetchList();
  } catch (error: any) {
    if (error !== "cancel") {
      ElMessage.error(error?.message || "批量审核失败");
    }
  } finally {
    loading.value = false;
  }
};

// 单个工单推送
const handleSinglePush = async (ticket: any) => {
  if (ticket.ticket_status !== "approved") {
    ElMessage.warning("只能推送已通过状态的工单");
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要推送工单 ${ticket.ticket_id} 到OA系统吗？`,
      "确认推送",
      {
        type: "warning",
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      }
    );

    loading.value = true;
    const result = await pushTickets({
      ticket_id: ticket.ticket_id,
    });

    ElMessage.success(result?.message || "推送成功");
    fetchList();
  } catch (error: any) {
    if (error !== "cancel") {
      ElMessage.error(error?.message || "推送失败");
    }
  } finally {
    loading.value = false;
  }
};

// 批量推送
const handleBatchPush = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请先选择要推送的工单");
    return;
  }

  // 检查是否都是已通过状态
  const canPush = selectedRows.value.every(
    (ticket) => ticket.ticket_status === "approved"
  );

  if (!canPush) {
    ElMessage.warning("只能推送已通过状态的工单");
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要批量推送 ${selectedRows.value.length} 个工单到OA系统吗？`,
      "确认批量推送",
      {
        type: "warning",
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      }
    );

    loading.value = true;
    const ticketIds = selectedRows.value.map((ticket) => ticket.ticket_id);

    const result = await pushTickets({
      ticket_ids: ticketIds,
      push_target: "oa",
    });

    ElMessage.success(result?.message || "批量推送成功");
    selectedRows.value = [];
    fetchList();
  } catch (error: any) {
    if (error !== "cancel") {
      ElMessage.error(error?.message || "批量推送失败");
    }
  } finally {
    loading.value = false;
  }
};

// 打开关闭工单弹窗
const handleOpenClose = (ticket: any) => {
  if (
    ticket.ticket_status !== "resolved" &&
    ticket.ticket_status !== "completed"
  ) {
    ElMessage.warning("只有已解决或已完成的工单才能关闭");
    return;
  }

  currentCloseTicket.value = ticket;
  closeForm.close_reason = "";
  closeForm.close_note = "";
  closeVisible.value = true;
};

// 提交关闭工单
const submitClose = async () => {
  if (!closeFormRef.value) return;

  try {
    await closeFormRef.value.validate();
  } catch (error) {
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要关闭工单 ${currentCloseTicket.value.ticket_id} 吗？关闭后不可再修改。`,
      "确认关闭",
      {
        type: "warning",
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      }
    );

    loading.value = true;
    const result = await closeTicket({
      ticket_id: currentCloseTicket.value.ticket_id,
      close_reason: closeForm.close_reason.trim(),
      close_note: closeForm.close_note.trim() || undefined,
    });

    ElMessage.success(result?.message || "工单关闭成功");
    closeVisible.value = false;
    fetchList();
  } catch (error: any) {
    if (error !== "cancel") {
      ElMessage.error(error?.message || "关闭工单失败");
    }
  } finally {
    loading.value = false;
  }
};

// 打开批量关闭弹窗
const openBatchClose = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请先选择要关闭的工单");
    return;
  }

  // 检查是否都是已解决或已完成状态
  const canClose = selectedRows.value.every(
    (ticket) =>
      ticket.ticket_status === "resolved" ||
      ticket.ticket_status === "completed"
  );

  if (!canClose) {
    ElMessage.warning("只能关闭已解决或已完成状态的工单");
    return;
  }

  batchCloseForm.close_reason = "";
  batchCloseForm.close_note = "";
  batchCloseVisible.value = true;
};

// 提交批量关闭
const submitBatchClose = async () => {
  if (!batchCloseFormRef.value) return;

  try {
    await batchCloseFormRef.value.validate();
  } catch (error) {
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要批量关闭 ${selectedRows.value.length} 个工单吗？关闭后不可再修改。`,
      "确认批量关闭",
      {
        type: "warning",
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      }
    );

    loading.value = true;
    const ticketIds = selectedRows.value.map((ticket) => ticket.ticket_id);

    const result = await batchCloseTickets({
      ticket_ids: ticketIds,
      close_reason: batchCloseForm.close_reason.trim(),
      close_note: batchCloseForm.close_note.trim() || undefined,
    });

    if (result?.data) {
      const { success_count, failed_count, total_count } = result.data;

      if (failed_count === 0) {
        ElMessage.success(`批量关闭成功！共处理 ${total_count} 个工单`);
      } else {
        ElMessage.warning(
          `批量关闭完成！成功 ${success_count} 个，失败 ${failed_count} 个`
        );

        // 显示失败详情
        if (result.data.results) {
          const failedList = result.data.results
            .filter((r: any) => r.status === "failed")
            .map((r: any) => `${r.ticket_id}: ${r.message}`)
            .join("\n");

          if (failedList) {
            ElMessage({
              message: `部分工单关闭失败：\n${failedList}`,
              type: "warning",
              duration: 5000,
              showClose: true,
            });
          }
        }
      }
    } else {
      ElMessage.success(result?.message || "批量关闭成功");
    }

    selectedRows.value = [];
    batchCloseVisible.value = false;
    fetchList();
  } catch (error: any) {
    if (error !== "cancel") {
      ElMessage.error(error?.message || "批量关闭失败");
    }
  } finally {
    loading.value = false;
  }
};

// 获取决策文本
const getDecisionText = (decision: "approved" | "rejected"): string => {
  const map: Record<string, string> = {
    approved: "通过",
    rejected: "拒绝",
  };
  return map[decision] || "";
};

// 初始化
onMounted(() => {
  fetchFilterOptions();
  fetchList();
  console.log(123, "1111111");
});
</script>

<style scoped lang="scss">
.ticket-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;

  .navbar-card {
    margin-bottom: 20px;
    border-radius: 8px;

    .navbar-content {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .page-title {
        font-size: 18px;
        font-weight: 600;
        margin: 0;
        color: #333;
      }

      .user-info {
        color: #666;
        font-size: 14px;
      }
    }
  }

  .stats-card,
  .filter-card,
  .action-bar-card,
  .table-card {
    margin-bottom: 20px;
    border-radius: 8px;
    border: 1px solid #f0f0f0;
  }

  .section-title {
    font-size: 16px;
    font-weight: 500;
    margin: 0 0 15px 0;
    color: #444;
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .stats-container {
    display: flex;
    gap: 15px;
    flex-wrap: wrap;
  }

  .filter-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;

    .toggle-filter-btn {
      color: #1890ff;
    }
  }

  .filter-content {
    padding: 5px 0;
  }

  .action-bar {
    display: flex;
    align-items: center;
    gap: 10px;
    // flex-wrap: wrap;

    .selected-count {
      margin-left: 10px;
      color: #666;
      font-size: 14px;
    }

    .sort-container {
      flex: 1;
      // width: 66vw;
      display: flex;
      justify-content: flex-end;
      align-items: center;
      gap: 5px;
      font-size: 14px;
    }
  }

  .export-btn {
    margin-left: 10px;
  }

  .batch-review-dialog {
    .selected-tickets {
      border: 1px solid #eee;
      padding: 10px;
      border-radius: 4px;
    }
  }

  @media (max-width: 768px) {
    .action-bar {
      flex-direction: column;
      align-items: flex-start;

      .sort-container {
        margin-left: 0;
        margin-top: 10px;
        width: 100%;
      }
    }
  }
}
</style>
